import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { ApplicationService, LoginData } from "../../../service/application.service";
import { AuthService } from "../../../service/auth.service";
import { User } from "../../../entity/user.model";
import { UserFarm } from "app/entity/user-farm.model";
import { Company } from "app/entity/company.model";
import { UserProfile } from "app/entity/user-profile.model";
import { Farm } from "app/entity/farm.model";

/**
 * 登录组件
 * 
 * @export
 * @class LoginComponent
 * @implements {OnInit}
 */
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public loginData: LoginData = { userName: "", password: "",auto: false, loginState: false };
  public loginError: any;
  public callbackURL:string;

  constructor(
    public router: Router,
    public application: ApplicationService,
    public authService: AuthService) {
    //如果程序的配置文件未加载首先加载配置文件
    if (this.application.initAppConfigDataCompleted) {
      if (this.application.loginData) {
        // this.loginData = this.application.loginData;
        if (this.application.loginData.auto) {
          this.loginData = this.application.loginData;
          this.onLogin();
        }
      }
    }
    else {
      this.application.initAppConfigData()
        .subscribe(
        next => {
          if (this.application.loginData) {
            if (this.application.loginData.auto) {
              this.loginData = this.application.loginData;
              this.onLogin();
            }
          }
        },
        error => {
          this.loginError = error;
        });
    }
  }

  public ngOnInit(): void {

  }
  /**
   * 
   * 
   * @memberof LoginComponent
   */
  public onLogin() {
    let callbackURL = window.sessionStorage.getItem('callbackURL')
    callbackURL = callbackURL?callbackURL:'';
    // console.log(callbackURL)
    this.authService.login(this.loginData.userName, this.loginData.password,callbackURL)
      .then(res => {
        if (!res) { return false; };
        if (this.authService.authReason) {
          this.loginData.loginState = true;
          this.application.loginData = this.loginData;
          this.application.userToken = res.token;          
          let currentUser: User = res.sysUser;
          let currentUserProfile: UserProfile = res.userProfile;
          let currentUserFarms: Farm[] = res.userFarmVOList;
          let currentCompany: Company = res.sysCompany;
          //-------------------------------
          let resCallbackURL = res.callbackURL;          
          let flag = res.flag;
          let sessionToken = res.sessionToken;
          
          //-------------------------------
          this.application.initApplicationData(currentUser, currentUserProfile, currentCompany, currentUserFarms)
            .subscribe(
            next => { 
              //导航到对应页面
              let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '';
              
              if(flag==0){
                if(callbackURL){
                  let url =resCallbackURL+"?token="+sessionToken;                                
                  window.location.href=url;
                }else{
                  this.router.navigate([redirect]);
                }                
              }else{  
                // console.log(redirect)              
                this.router.navigate([redirect]);
              }
              // this.router.navigate([redirect]);
            },
            error => {
              this.loginError = error;
            });

        }
        else {
          this.application.loginData = null;
          // this.loginError = this.authService.authError;
          this.loginError = '用户名或密码错误!';

        }
      })
      .catch(error => {
        this.loginError = error;
        
      })
  }
  onKeyup(){
    this.loginError = '';
  }
  /**
   * 回车键登录
   * 
   * @memberof LoginComponent
   */
  public onKeyLogin($event): void {
    if ($event.keyCode == 13) {
      this.onLogin()
    }
  }
  /**
   * 下次自动登录
   * 
   * @private
   * @param {any} event 
   * 
   * @memberOf LoginComponent
   */
  public onRememberCheck(event: MouseEvent): void {
    this.loginData.auto = !this.loginData.auto;

  }
}




// WEBPACK FOOTER //
// ./src/app/module/security/login/login.component.ts